package com.ruoyi.netty.client;

import com.ruoyi.netty.client.initializer.NettyClientinitializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author: [青衫] 'QSSSYH@QQ.com'
 * @Date: 2019-07-31 20:04
 * @Description: < 描述 >
 */
@Component
public class NettyClient
	{

		@Autowired
		private NettyClientinitializer nettyClientinitializer;

		public void serverRun()
			{

				// 创建监听对象
				EventLoopGroup eventExecutors = new NioEventLoopGroup();
				try
					{
						Bootstrap bootstrap = new Bootstrap();
						bootstrap.group(eventExecutors).channel(NioSocketChannel.class)
								// 这里使用的是handler handler()和childHandler()的区别是主要服务监听线程组 和处理线程组
								.handler(nettyClientinitializer);

						ChannelFuture channelFuture = bootstrap.connect("localhost", 8185).sync();
						// 可绑定多端口监听 当前版本只简单处理 只绑定一个端口
						System.err.println("Netty客户端已经启动,已连接至端口:" + 8185);
						channelFuture.channel().closeFuture().sync();
					} catch (InterruptedException e)
					{
						e.printStackTrace();

					} finally
					{
						// 关闭连接
						eventExecutors.shutdownGracefully();

					}

			}

	}
